package com.besttone.http;

import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalBase64;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParser;

import com.besttone.search.Client;
import com.besttone.search.ServerListener;
import com.besttone.search.model.ChResultInfo;
import com.besttone.search.model.OrgInfo;
import com.besttone.search.model.RequestInfo;
import com.besttone.search.util.Constants;
import com.besttone.search.util.XmlHelper;

import android.util.Log;
import android.util.Xml;

public class WebServiceHelper {
	private static final String TAG = "WebServiceHelper";
	//命名空间     
	private static final String serviceNameSpace="http://ws.besttone.com/";
	
	//调用方法(获得支持的城市)  
	//private static final String methodName="SearchChInfo";
	private static final String methodName="searchChNewInfo";
	
	private ChResultInfo resultInfo;
	
	private int i = 0;
	private List<Map<String, Object>> list;
	
	public static interface WebServiceListener {
		public void onWebServiceSuccess();
		public void onWebServiceFailed();
	}
	
	public void setmListener(WebServiceListener mListener) {
		this.mListener = mListener;
	}

	private WebServiceListener 	mListener;
	 
	 public List<Map<String, Object>> searchChInfo(RequestInfo rqInfo){
		 Long t1 = System.currentTimeMillis();
		 list = new LinkedList<Map<String, Object>>();
		//返回的查询结果
		 String result =null;
		 //实例化SoapObject对象        
		 SoapObject request=new SoapObject(serviceNameSpace, methodName);
		 
		 //假设方法有参数的话,设置调用方法参数
		 String rqXml = XmlHelper.getRequestXml(rqInfo);
		 
		 request.addProperty("xml", rqXml);
		 request.addProperty("name",Constants.chName);
		 request.addProperty("key",Constants.chKey);
		 
		 
		 //设置SOAP请求信息(参数部分为SOAP协议版本号，与你要调用的webService中版本号一致)
		//获得序列化的Envelope
		 SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER10);
		//设置是否调用的是dotNet开发的
		 envelope.dotNet = false;
		 envelope.bodyOut=request;
		 envelope.setOutputSoapObject(request);
         
         //注册Envelope
         (new MarshalBase64()).register(envelope);
         
         //构建传输对象，并指明WSDL文档URL
         //Android传输对象
         HttpTransportSE transport=new HttpTransportSE(Constants.serviceURL); 
         transport.debug=true;
         
         //调用WebService(其中参数为1：命名空间+方法名称，2：Envelope对象):
         String soapAction = serviceNameSpace+methodName;
         
         try {
             transport.call(soapAction, envelope);
             
             //解析返回数据
             Object resultObj = envelope.getResponse();
             result = resultObj.toString();
             
             parseChInfo(result);
		} catch (Exception e) {
			e.printStackTrace();
			Log.v(TAG, "获取XML出错");
		}
		Long t2 = System.currentTimeMillis();
		Log.v(TAG, "获取查号信息耗时"+(t2-t1)+"毫秒");
		return list;
	 }
	 
	 public void parseChInfo(String xmlString) {
			Map<String, Object> map = new HashMap<String, Object>();
		 
		 
		 InputStream inputStream=null;
		 //获得XmlPullParser解析器
		 XmlPullParser xmlParser = Xml.newPullParser();
	        try {
	            //得到文件流，并设置编码方式
	        	xmlParser.setInput(new StringReader(xmlString));
	            //获得解析到的事件类别，这里有开始文档，结束文档，开始标签，结束标签，文本等等事件。
	            int evtType=xmlParser.getEventType();
	            
	            List<OrgInfo> orgList = null;
	            OrgInfo info = null;
	            String propertyName = null;
	            String propertyValue = null;
	         //一直循环，直到文档结束    
	         while(evtType!=XmlPullParser.END_DOCUMENT){ 
	        	 String tag = xmlParser.getName(); 
	            switch(evtType){ 
	            case XmlPullParser.START_TAG:
	                //如果是river标签开始，则说明需要实例化对象了
	                if (tag.equalsIgnoreCase("SearchResult")) { 
	                	resultInfo = new ChResultInfo();
	                	break;
	                }
	                if (tag.equalsIgnoreCase("BDCDataSource")) { 
	                	resultInfo.setSource(xmlParser.nextText());
	                	break;
	                }
	                if (tag.equalsIgnoreCase("BDCSearchflag")) { 
	                	resultInfo.setSearchFlag(xmlParser.nextText());
	                	break;
	                }
	                if (tag.equalsIgnoreCase("ResultCount")) {
	                	String cnt = xmlParser.nextText();
	                	break;
	                }
	                if (tag.equalsIgnoreCase("ResultTime")) { 
	                	String time = xmlParser.nextText();
	                	break;
	                }
	                if (tag.equalsIgnoreCase("SingleResult")) { 
	                	map = new HashMap<String, Object>();
						break;
	                }
	                if (tag.equalsIgnoreCase("propertyName")) {
	                	propertyName = xmlParser.nextText();
	                	break;
	                }
	                if (tag.equalsIgnoreCase("propertyValue")) {
	                	propertyValue = xmlParser.nextText();
	                	if(propertyName!=null && "产品序列号".equals(propertyName)) {
//	                		if(propertyValue!=null && !Constants.SPACE.equals(propertyValue)){
//	                			info.setChId(Integer.valueOf(propertyValue));
//	                		}
	                		if(propertyValue==null || Constants.SPACE.equals(propertyValue)) {
	                			propertyValue = Constants.SPACE;
	                		}
	                		map.put("chId", propertyValue);
	                	}
	                	
	                	if(propertyName!=null && "公司名称".equals(propertyName)) {
	                		if(propertyValue==null || Constants.SPACE.equals(propertyValue)) {
	                			propertyValue = Constants.SPACE;
	                		}
	                		map.put("name", propertyValue);
	                	}
	                	
	                	if(propertyName!=null && "首查电话".equals(propertyName)) {
	                		if(propertyValue==null || Constants.SPACE.equals(propertyValue)) {
	                			propertyValue = Constants.SPACE;
	                		}
	                		map.put("tel", propertyValue);
	                	}
	                	
	                	if(propertyName!=null && "地址".equals(propertyName)) {
	                		if(propertyValue==null || Constants.SPACE.equals(propertyValue)) {
	                			propertyValue = Constants.SPACE;
	                		}
	                		map.put("addr", propertyValue);
	                	}
	                	
	                	if(propertyName!=null && "ORG_ID".equals(propertyName)) {
	                		map.put("orgId", propertyValue);
	                	}
	                	
	                	if(propertyName!=null && "所属城市".equals(propertyName)) {
	                		map.put("city", Constants.getCity(propertyValue));
	                	}
	                	
	                	if(propertyName!=null && "Region_Cede".equals(propertyName)) {
	                		map.put("regionCode", propertyValue);
	                	}
	                	
	                	if(propertyName!=null && "IS_DC".equals(propertyName)) {
	                		map.put("isDc", propertyValue);
	                	}
	                	
	                	if(propertyName!=null && "IS_DF".equals(propertyName)) {
	                		map.put("isDf", propertyValue);
	                	}
	                	
	                	if(propertyName!=null && "QYMP".equals(propertyName)) {
	                		map.put("isQymp", propertyValue);
	                	}
	                	
	                	propertyName = null;
	                	propertyValue = null;
	                }
	                break;
	                
	           case XmlPullParser.END_TAG:
	             //如果遇到river标签结束，则把river对象添加进集合中
	        	   if (tag.equalsIgnoreCase("SingleResult")) {
	        		   if(map.get("addr")==null) {
	        			   map.put("addr", Constants.SPACE);
	        		   }
	        		   if(map.get("tel")==null) {
	        			   map.put("tel", Constants.SPACE);
	        		   }
	            	   list.add(map);
	               }
	                break; 
	                default:break;
	            }
	            //如果xml没有结束，则导航到下一个river节点
	            evtType=xmlParser.next();
	         }
	        } catch (Exception e) {
	            e.printStackTrace();
	            Log.v(TAG, "xml解析出错"+e.getMessage());
	        }
	 }
	 
	public void sendRequest(final ServerListener listener, final RequestInfo rqInfo) {
		
		Client.getThreadPoolForRequest().execute(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub

				try {
					Thread.sleep(1000);
				} catch (Exception e) {

				}

				list = searchChInfo(rqInfo);
				listener.serverDataArrived(list, false);	

			
			}
		});

	}
	
	public ArrayList<String> getAssociateList(String key) {
		Long t1 = System.currentTimeMillis();
		ArrayList<String> resultAssociateList = new ArrayList<String>();
//		new ArrayList<String>();
		//返回的查询结果
		 String result =null;
		 //实例化SoapObject对象        
		 SoapObject request=new SoapObject(serviceNameSpace, Constants.associate_method);
		 
		 //假设方法有参数的话,设置调用方法参数
		 StringBuilder sb = new StringBuilder("");
		if (key != null) {
			sb.append("<ChKeyInpara>");
			sb.append("<content><![CDATA[" + key + "]]></content>");
			sb.append("</ChKeyInpara>");
		}

		 request.addProperty("xml", sb.toString());
		 request.addProperty("name",Constants.chName);
		 request.addProperty("key",Constants.chKey);
		 
		 
		 //设置SOAP请求信息(参数部分为SOAP协议版本号，与你要调用的webService中版本号一致)
		//获得序列化的Envelope
		 SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER10);
		//设置是否调用的是dotNet开发的
		 envelope.dotNet = false;
		 envelope.bodyOut=request;
		 envelope.setOutputSoapObject(request);
        
        //注册Envelope
        (new MarshalBase64()).register(envelope);
        
        //构建传输对象，并指明WSDL文档URL
        //Android传输对象
        HttpTransportSE transport=new HttpTransportSE(Constants.serviceURL); 
        transport.debug=true;
        
        //调用WebService(其中参数为1：命名空间+方法名称，2：Envelope对象):
        String soapAction = serviceNameSpace+Constants.associate_method;
        try {
            transport.call(soapAction, envelope);
            
            //解析返回数据
            Object resultObj = envelope.getResponse();
            result = resultObj.toString();
            
            resultAssociateList = parseKeywordInfo(result);
		} catch (Exception e) {
			e.printStackTrace();
			Log.v(TAG, "关键词联想获取出错");
		}
		Long t2 = System.currentTimeMillis();
		Log.v(TAG, "关键词联想获取耗时"+(t2-t1)+"毫秒");
				
//		if(mListener!=null)
//			mListener.onWebServiceSuccess();
		
		return resultAssociateList;
	}
	
	public ArrayList<String> parseKeywordInfo(String xmlString) {
		Map<String, Object> map = new HashMap<String, Object>();
		ArrayList<String> resultList = new ArrayList<String>();
		
		InputStream inputStream=null;
		 //获得XmlPullParser解析器
		 XmlPullParser xmlParser = Xml.newPullParser();
		 try{
	            //得到文件流，并设置编码方式
	        	xmlParser.setInput(new StringReader(xmlString));
	            //获得解析到的事件类别，这里有开始文档，结束文档，开始标签，结束标签，文本等等事件。
	            int evtType=xmlParser.getEventType();
	            
			// 一直循环，直到文档结束
			while (evtType != XmlPullParser.END_DOCUMENT) {
				String tag = xmlParser.getName();
				switch (evtType) {
				case XmlPullParser.START_TAG:
					// 如果是river标签开始，则说明需要实例化对象了
					if (tag.equalsIgnoreCase("ChKeyResult")) {
						map = new HashMap<String, Object>();
						break;
					}
					if (tag.equalsIgnoreCase("resultNum")) {
						String resultNum = xmlParser.nextText();
						map.put("resultNum", resultNum);
						break;
					}
					if (tag.equalsIgnoreCase("result")) {
						String result = xmlParser.nextText();
						map.put("result", result);
						break;
					}
					if (tag.equalsIgnoreCase("searchTime")) {
						String searchTime = xmlParser.nextText();
						map.put("searchTime", searchTime);
						break;
					}
	                if (tag.equalsIgnoreCase("ChKeyList")) { 
						break;
	                }
	                if (tag.equalsIgnoreCase("searchKey")) {
	                	String searchKey = xmlParser.nextText();
	                	resultList.add(searchKey);
	                	break;
	                }
					break;
				case XmlPullParser.END_TAG:
					// 如果遇到river标签结束，则把river对象添加进集合中
					if (tag.equalsIgnoreCase("ChKeyResult")) {
						map.put("resultList", resultList);
					}
					break;
				default:
					break;
				}
				// 如果xml没有结束，则导航到下一个river节点
				evtType = xmlParser.next();
			}
		 } catch (Exception e) {
	            e.printStackTrace();
	            Log.v(TAG, "xml解析出错"+e.getMessage());
	        }
		 
		 return resultList;
	}

}
